#!/usr/bin/env python
#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
'''find_torrent_descriptions -- find related contents descriptions in Clearview logs.'''

import bulk_inserter
import log_parser

import libtorrent
import psycopg2


import sys

bdecode = libtorrent.bdecode


def sum_if_not_both_none(a,b):
  if a is None and b is None:
    return None

  sum = 0
  if a is not None:
    sum += a
  if b is not None:
    sum += b

  return sum


class LogProcessor(object):
  def __init__(self, conn, table_name):
    # Remove extra stuff for "production".
#     query = '''INSERT INTO torrent_descs_new
#                (name, size, rand, hash, tracker, cnet,
#                seeders, leechers, dhtkey) VALUES'''
    query = '''INSERT INTO %s
               (name, size, hash, seeders, leechers,
                peers, dhtkey) VALUES''' % table_name
    self.conn = conn
    self.inserter = bulk_inserter.BulkInserter(conn, query, 7)

  def process_record(self, key, time, version, originator, value):
    if value[0] != 'd':
      return
    try:
      val = bdecode(value)
    except RuntimeError:
      val = None
    if val is not None and 's' in val and 'r' in val and 'd' in val and 'h' in val:#('h' in val or 't' in val):
      hash = val.get('h')
      if hash is not None:
        hash = psycopg2.Binary(hash)
      # Remove extra stuff for "production."
#      tracker = val.get('t')
#       self.inserter.insert((val['d'], val['s'], val['r'], hash,
#                             tracker, val.get('c'), val.get('z'),
#                             val.get('l'), psycopg2.Binary(key)))
      seeders = val.get('z')
      leechers = val.get('l')
      peers = sum_if_not_both_none(seeders, leechers)

      self.inserter.insert((val['d'], val['s'], hash, seeders, leechers, peers,
                           psycopg2.Binary(key)))

  def done(self):
    self.inserter.done()

from cytorrent_desc_proc import LogProcessor

def main(argv):
  conn = psycopg2.connect('dbname=dhtsearch')

  
  lp = LogProcessor(conn)

  for log in argv[1:]:
    lst = log_parser.get_stores(log, True)
    for (key, time, version, originator, value) in lst:
      lp.process_record(key, time, version, originator, value)

#    print 'finished', log
  lp.done()
  conn.commit()
  conn.close()

if __name__ == '__main__':
  main(sys.argv)
